package com.lill.support.aspect;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.lill.auth2.constant.AuthBean;
import com.lill.auth2.util.TwiceToken;
import com.lill.common.component.util.IpUtil;
import com.lill.support.annotation.AuthTokenTwice;

@Component
public class HandlerTokenTwiceResolver implements HandlerMethodArgumentResolver {
	
	public boolean supportsParameter(MethodParameter parameter) {
		return parameter.hasMethodAnnotation(AuthTokenTwice.class);
	}

	public Object resolveArgument(MethodParameter parameter,ModelAndViewContainer mavContainer, NativeWebRequest webRequest,WebDataBinderFactory binderFactory) throws Exception {
		AuthBean authBean=null;
		String authToken=webRequest.getHeader("Authorization");
		if(StringUtils.isNotEmpty(authToken)){
			authBean=TwiceToken.decryptToken(authToken);
		}
		if(null!=authBean){
			HttpServletRequest request=(HttpServletRequest) webRequest.getNativeRequest();
			String accessUrl=request.getRequestURI();
			String ipAddress=IpUtil.getRequestUserIp(request);
			if(StringUtils.isNotEmpty(accessUrl)&&StringUtils.isNotEmpty(ipAddress)
					&&accessUrl.equals(authBean.getAccessUrl())&&ipAddress.equals(authBean.getIpAdress())){
			}else{
				throw new RuntimeException("token verify failure");
			}
		}else{
			throw new RuntimeException("token verify failure");
		}
		return authBean;
	}

}
